package com.sxj.corejava.code15_反射;

import java.lang.reflect.Field;

/**
 * @author 石小俊
 */
public class Test04_操作属性 {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Class c = User.class;
        System.out.println("*************************获取当前类以及其父类中所有public修饰的属性*************************");
        // 包含当前类与父类
        Field[] fields = c.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }

        System.out.println("*************************获取当前类中所有属性,不区分修饰符*************************");
        // 只有当前类
        Field[] declaredFields = c.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }

        System.out.println("*************************获取当前类以及其父类中指定的public修饰的属性*************************");
        Field usernameField = c.getField("username");
        Field nameField = c.getField("name");
        System.out.println(usernameField);
        System.out.println(nameField);

        System.out.println("*************************获取当前类中指定的属性,不区分修饰符*************************");
        Field idField = c.getDeclaredField("id");
        System.out.println(idField);
        // 无法访问父类的
        // Field ageField = c.getDeclaredField("age");
        // System.out.println(ageField);

        System.out.println("*************************赋值操作*************************");
        // 操作属性有赋值与取值的操作,通过Field对象进行操作
        User user = new User();
        usernameField.set(user, "admin");

        User user2 = new User();
        usernameField.set(user2, "alice");

        System.out.println("*************************取值操作*************************");
        System.out.println("user对象的username属性值为:" + usernameField.get(user));
        System.out.println("user2对象的username属性值为:" + usernameField.get(user2));

        System.out.println("*************************操作私有属性*************************");
        idField.setAccessible(true);
        idField.set(user, 1);
        System.out.println(idField.get(user));

    }
}
